<template>
    <page-container title="任务日志管理">
      <div class="data-task-list">
        <!-- 操作栏 -->
        <div class="operation-bar">
          <el-button type="primary" @click="openEditDialog()">新增数据任务日志</el-button>
          <el-input
            v-model="searchId"
            placeholder="请输入任务日志id"
            style="width: 200px; margin-left: 10px"
            @keyup.native.enter="handleSearch"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="handleSearch" />
            </template>
          </el-input>
        </div>

        <!-- 数据表格 -->
        <el-table
        :data="tableData"
        style="width: 100%"
        :fit="true"
        :border="true"
        header-height="50"
        v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="100" />
          <el-table-column prop="taskId" label="关联的数据任务(id)" min-width="150">
            <template slot-scope="{ row }">
              {{ getTaskName(row.taskId) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" min-width="100" />
          <el-table-column prop="startTime" label="任务开始执行时间" min-width="150" />
          <el-table-column prop="endTime" label="任务结束执行时间" min-width="150" />
          <el-table-column prop="resultFilePath" label="任务执行结果文件路径" min-width="200" />
          <el-table-column prop="message" label="日志信息/错误信息" min-width="200" />
          <el-table-column label="操作" width="240" flex="right" align="center">
            <template slot-scope="{ row }">
              <el-button type="primary" size="mini" @click="openEditDialog(row)"
                >编辑</el-button
              >
              <el-button type="danger" size="mini" @click="handleDelete(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          class="pagination"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
        />

        <!-- 新增/编辑弹窗 -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          width="600px"
          @close="resetForm"
        >
          <el-form
            :model="form"
            :rules="rules"
            ref="logForm"
            label-width="120px"
            v-loading="submitLoading"
          >
            <el-form-item label="关联任务" prop="taskId">
              <el-select v-model="form.taskId" placeholder="请选择关联任务" style="width: 100%;">
                <el-option
                  v-for="item in taskOptions"
                  :key="item.id"
                  :label="item.name ? (item.name + '（' + item.id + '）') : item.id"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
                <el-option label="成功" value="成功" />
                <el-option label="失败" value="失败" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-input v-model="form.startTime" placeholder="请输入任务开始执行时间" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-input v-model="form.endTime" placeholder="请输入任务结束执行时间" />
            </el-form-item>
            <el-form-item label="结果文件路径" prop="resultFilePath">
              <el-input v-model="form.resultFilePath" placeholder="请输入结果文件路径" />
            </el-form-item>
            <el-form-item label="日志/错误信息" prop="message">
              <el-input v-model="form.message" type="textarea" placeholder="请输入日志或错误信息" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="submitForm">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </page-container>
  </template>
<script>
import PageContainer from '@/components/PageContainer.vue'
import {
  getTaskLogList,
  addTaskLog,
  updateTaskLog,
  deleteTaskLog,
  getTaskLogById
} from '@/api/tasklog'
import { getTaskList } from '@/api/task'

export default {
  name: 'DataLogList',
  components: {
    PageContainer
  },
  data () {
    return {
      tableData: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      searchId: '',
      dialogVisible: false,
      dialogTitle: '新增数据任务日志',
      submitLoading: false,
      form: {
        id: null,
        taskId: '',
        status: '',
        startTime: '',
        endTime: '',
        resultFilePath: '',
        message: ''
      },
      rules: {
        taskId: [
          { required: true, message: '请选择关联任务', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请输入开始时间', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请输入结束时间', trigger: 'blur' }
        ]
      },
      taskOptions: []
    }
  },
  created () {
    this.loadData()
    this.loadTaskOptions()
  },
  methods: {
    // 加载数据
    async loadData () {
      this.loading = true
      try {
        const params = {
          current: this.currentPage,
          size: this.pageSize,
          id: this.searchId || undefined
        }
        if (this.searchId) {
          // 如果有searchId，直接查详情接口
          const res = await getTaskLogById(this.searchId)
          if (res.code === 200 && res.data) {
            this.tableData = [res.data]
            this.total = 1
          } else {
            this.tableData = []
            this.total = 0
            this.$message.warning(res.msg || '未找到该任务日志ID的数据')
          }
        } else {
          // 正常分页
          const res = await getTaskLogList(params)
          if (res.code === 200) {
            this.tableData = res.data.records || []
            this.total = res.data.total || 0
          } else {
            this.$message.error(res.msg || '获取任务日志列表失败')
            this.tableData = []
            this.total = 0
          }
        }
      } catch (error) {
        this.$message.error('获取任务日志列表失败: ' + (error.message || '未知错误'))
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleSearch () {
      // 重置到第一页
      this.currentPage = 1
      console.log('searchId', this.searchId)
      // 验证输入的id是否为数字
      if (this.searchId && !/^\d+$/.test(this.searchId)) {
        this.$message.warning('请输入正确的任务日志ID')
        return
      }
      // 加载数据
      this.loadData()
    },
    // 分页
    handlePageChange (page) {
      this.currentPage = page
      this.loadData()
    },
    // 打开编辑弹窗
    openEditDialog (row) {
      if (row) {
        this.dialogTitle = '编辑数据任务日志'
        this.dialogVisible = true
        this.getDetail(row.id)
      } else {
        this.dialogTitle = '新增数据任务日志'
        this.dialogVisible = true
        this.resetForm()
        if (this.taskOptions.length === 0) {
          this.loadTaskOptions().then(() => {
            if (this.taskOptions.length === 0) {
              this.$message.warning('未获取到任务列表，请先添加任务')
            }
          })
        }
      }
    },
    // 获取详情
    async getDetail (id) {
      try {
        const res = await getTaskLogById(id)
        if (res.code === 200) {
          this.form = { ...res.data }
          this.dialogVisible = true
        } else {
          this.$message.error(res.msg || '获取日志详情失败')
        }
      } catch (error) {
        this.$message.error('获取日志详情失败: ' + (error.message || '未知错误'))
      }
    },
    // 删除
    async handleDelete (id) {
      this.$confirm('确认删除该日志？', '温馨提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        try {
          const res = await deleteTaskLog(id)
          if (res.code === 200) {
            this.$message.success('删除成功！')
            this.loadData()
          } else {
            this.$message.error('删除失败：' + (res.msg || '未知错误'))
          }
        } catch (error) {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      })
    },
    // 重置表单
    resetForm () {
      this.form = {
        id: null,
        taskId: '',
        status: '',
        startTime: '',
        endTime: '',
        resultFilePath: '',
        message: ''
      }
    },
    // 提交表单
    submitForm () {
      this.$refs.logForm.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        try {
          let res
          if (this.form.id) {
            res = await updateTaskLog(this.form)
          } else {
            res = await addTaskLog(this.form)
          }
          if (res.code === 200) {
            this.$message.success(this.form.id ? '修改成功' : '添加成功')
            this.dialogVisible = false
            this.loadData()
          } else {
            this.$message.error(res.msg || (this.form.id ? '修改失败' : '添加失败'))
          }
        } catch (error) {
          this.$message.error((this.form.id ? '修改失败' : '添加失败') + ': ' + (error.message || '未知错误'))
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 加载任务选项
    async loadTaskOptions () {
      try {
        const res = await getTaskList({ current: 1, size: 1000 })
        console.log('rrrres', res)
        if (res.code === 200) {
          this.taskOptions = res.data.records || []
          console.log('taskOptions', this.taskOptions)
        }
      } catch (e) {
        this.taskOptions = []
      }
    },
    // 获取任务标签
    getTaskName (taskId) {
      const task = this.taskOptions.find(item => item.id === taskId)
      return task ? (task.name ? `${task.name}（${task.id}）` : task.id) : taskId
    }
  }
}
</script>
  <style scoped>
  .operation-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: end;
  }
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  .el-table th{
    vertical-align: middle;
    line-height: 60px;
  }
  .data-task-list {
    width: 100%;
    padding: 0;
    margin: 0;
  }
  .data-task-list >>> .el-table th {
    height: 100px;
    line-height: 100px;
    vertical-align: middle;
    padding: 0;
  }
  </style>
